//
//  SWChildInfoSupplementViewController.swift
//  ChildStory
//
//  Created by linhan on 16/8/30.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWChildInfoSupplementViewController: SWBaseViewController,SWAPIComponent
{
    private var _gender:Int = SWGender.Unknow.rawValue
    private var _genderGroup:SWRadioButtonGroup = SWRadioButtonGroup()
    private var _roleGroup:SWRadioButtonGroup = SWRadioButtonGroup()
    
    private let TextFieldHeight:CGFloat = 50
    private let PlaceholderColor:UIColor = UIColor(hex: 0xababab)
    private let InputColor:UIColor = UIColor.darkGray
    private let TextFieldBorderColor:UIColor = UIColor(hex: 0xd0d0d0)
    
    private var _textFieldWidth:CGFloat = 0
    private var _textFieldLeftMargin:CGFloat = 0
    
    
    lazy private var _toolBar:UIToolbar = UIToolbar()
    lazy private var _datePicker:UIDatePicker = UIDatePicker()
    
    private var _dateTextField:ImageTextField = ImageTextField()
    private var _nameTextField:ImageTextField = ImageTextField()
    
    private class RadioButton:UIButton,SWIRadioButton
    {
        var beSelected:Bool{
            get{
                return isEnabled
            }
            set{
                isEnabled = !newValue
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool)
    {
        super.viewDidAppear(animated)
        if appearedFirstTime
        {
            appearedFirstTime = false
            //当到资料补全页来，说明已经注册成功，之前的注册登录页面已经不再需要了
            navigationController?.viewControllers = [self]
        }
    }
    
    deinit
    {
        trace("DEINIT UserInfoSupplementViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        title = "宝宝信息填写"
        view.backgroundColor = UIColor.white
        
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        view.addGestureRecognizer(tapGesture)
        
        _textFieldWidth = view.width * 0.733
        _textFieldLeftMargin = (view.width - _textFieldWidth) * 0.5
        
        
        //名称
        var lastBottom:CGFloat = createNameTextField(y: navigationBarBottom + 36)
        //生日
        lastBottom = createDateTextField(y: lastBottom + 25)
        //性别
        lastBottom = createGenderView(y:lastBottom + 25)
        //角色
        lastBottom = createRoleView(y:lastBottom + 25)
        
        //完成
        let createBtn:UIButton = UIButton(type:.system)
        createBtn.setTitleColor(UIColor.white, for: .normal)
        createBtn.setTitle("完成", for: .normal)
        createBtn.titleLabel?.font = UIFont.systemFont(ofSize:18)
        createBtn.backgroundColor = UIColor(hex:0xf46363)
        createBtn.layer.cornerRadius = 4
        createBtn.layer.masksToBounds = true
        createBtn.frame = CGRectMake(_textFieldLeftMargin, lastBottom + 40, _textFieldWidth, 50)
        createBtn.addTarget(self, action: #selector(createBtnTapped), for: .touchUpInside)
        view.addSubview(createBtn)
    }
    
    private func createNameTextField(y:CGFloat) -> CGFloat
    {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 18)
        label.text = "宝宝昵称"
        label.textColor = UIColor(hex: 0x303332)
        label.sizeToFit()
        label.frame = CGRectMake(_textFieldLeftMargin, y, label.width, label.height)
        view.addSubview(label)
        
        //名称
        _nameTextField.frame = CGRectMake(_textFieldLeftMargin, label.bottom + 18, _textFieldWidth, TextFieldHeight)
        _nameTextField.textInset = UIEdgeInsetsMake(0, 18, 0, 18)
        _nameTextField.font = UIFont.systemFont(ofSize:14)
        _nameTextField.textAlignment = .left
        _nameTextField.clearButtonMode = .whileEditing
        _nameTextField.attributedPlaceholder = NSMutableAttributedString(string: "乳名/爱称", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _nameTextField.textColor = InputColor
        _nameTextField.layer.borderColor = TextFieldBorderColor.cgColor
        _nameTextField.layer.borderWidth = 1
        _nameTextField.layer.cornerRadius = 4
        _nameTextField.layer.masksToBounds = true
        view.addSubview(_nameTextField)
        return _nameTextField.bottom
    }
    
    private func createDateTextField(y:CGFloat) -> CGFloat
    {
        _datePicker.frame = CGRectMake(0, 0, view.width, 150)
        _datePicker.datePickerMode = .date
        
        
        //工具栏
        let completeBtn = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(completeBtnTapped))
        let cancelBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelBtnTapped))
        let spaceBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        
        _toolBar.sizeToFit()
        _toolBar.tintColor = UIColor.darkGray
        _toolBar.barTintColor = UIColor.white
        _toolBar.items = [cancelBtn, spaceBtn, completeBtn]
        
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 18)
        label.text = "生日"
        label.textColor = UIColor(hex: 0x303332)
        label.sizeToFit()
        label.frame = CGRectMake(_textFieldLeftMargin, y, label.width, label.height)
        view.addSubview(label)
        
        //生日
        _dateTextField.frame = CGRectMake(_textFieldLeftMargin, label.bottom + 18, _textFieldWidth, TextFieldHeight)
        _dateTextField.inputAccessoryView = _toolBar
        _dateTextField.inputView = _datePicker
        _dateTextField.textInset = UIEdgeInsetsMake(0, 18, 0, 18)
        _dateTextField.font = UIFont.systemFont(ofSize:14)
        _dateTextField.textAlignment = .left
        _dateTextField.attributedPlaceholder = NSMutableAttributedString(string: "宝宝生日", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _dateTextField.textColor = InputColor
        _dateTextField.layer.borderColor = TextFieldBorderColor.cgColor
        _dateTextField.layer.borderWidth = 1
        _dateTextField.layer.cornerRadius = 4
        _dateTextField.layer.masksToBounds = true
        view.addSubview(_dateTextField)
        return _dateTextField.bottom
    }
    
    private func createGenderView(y:CGFloat) -> CGFloat
    {
        let genderLabel = UILabel()
        genderLabel.text = "宝宝性别"
        genderLabel.font = UIFont.systemFont(ofSize: 18)
        genderLabel.textColor = UIColor(hex: 0x303332)
        genderLabel.sizeToFit()
        genderLabel.frame = CGRectMake(_textFieldLeftMargin, y, genderLabel.width, genderLabel.height)
        view.addSubview(genderLabel)
        
        let genderBtnView = UIView(frame: CGRectMake(0, genderLabel.bottom + 18, view.width, 0))
        view.addSubview(genderBtnView)
        
        let boyBtn:RadioButton = createRadioButton(title: "男")
        boyBtn.tag = SWGender.Male.rawValue
        boyBtn.frame = CGRectMake(_textFieldLeftMargin, 0, boyBtn.width, boyBtn.height)
        boyBtn.addTarget(self, action: #selector(genderBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(boyBtn)
        
        let girlBtn:RadioButton = createRadioButton(title: "女")
        girlBtn.tag = SWGender.Female.rawValue
        girlBtn.frame = CGRectMake(boyBtn.right + 46, 0, girlBtn.width, girlBtn.height)
        girlBtn.addTarget(self, action: #selector(genderBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(girlBtn)
        genderBtnView.height = girlBtn.height
        
        _genderGroup.addItems([boyBtn, girlBtn])
        
        return genderBtnView.bottom
    }
    
    private func createRoleView(y:CGFloat) -> CGFloat
    {
        let genderLabel = UILabel()
        genderLabel.text = "您是宝宝的"
        genderLabel.font = UIFont.systemFont(ofSize: 18)
        genderLabel.textColor = UIColor(hex: 0x303332)
        genderLabel.sizeToFit()
        genderLabel.frame = CGRectMake(_textFieldLeftMargin, y, genderLabel.width, genderLabel.height)
        view.addSubview(genderLabel)
        
        let genderBtnView = UIView(frame: CGRectMake(0, genderLabel.bottom + 18, view.width, 0))
        view.addSubview(genderBtnView)
        
        let fatherBtn:RadioButton = createRadioButton(title: "爸爸")
        fatherBtn.tag = SWRole.Father.rawValue
        fatherBtn.frame = CGRectMake(_textFieldLeftMargin, 0, fatherBtn.width, fatherBtn.height)
        fatherBtn.addTarget(self, action: #selector(roleBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(fatherBtn)
        
        let motherBtn:RadioButton = createRadioButton(title: "妈妈")
        motherBtn.tag = SWRole.Mother.rawValue
        motherBtn.frame = CGRectMake(fatherBtn.right + 25, 0, motherBtn.width, motherBtn.height)
        motherBtn.addTarget(self, action: #selector(roleBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(motherBtn)
        
        let otherBtn:RadioButton = createRadioButton(title: "其他")
        otherBtn.tag = SWRole.Other.rawValue
        otherBtn.frame = CGRectMake(motherBtn.right + 25, 0, otherBtn.width, otherBtn.height)
        otherBtn.addTarget(self, action: #selector(roleBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(otherBtn)
        genderBtnView.height = otherBtn.height
        
        _roleGroup.addItems([fatherBtn, motherBtn, otherBtn])
        
        return genderBtnView.bottom
    }
    
    private func createRadioButton(title:String) -> RadioButton
    {
        let margin:CGFloat = 15
        let button:RadioButton = RadioButton(type:.custom)
        button.setTitle(title, for: .normal)
        button.setTitle(title, for: .disabled)
        button.titleEdgeInsets = UIEdgeInsetsMake(0, margin, 0, 0)
        button.setTitleColor(UIColor(hex:0x2f3231), for: .normal)
        button.setImage(UIImage(named: "child_radio_normal"), for: .normal)
        button.setImage(UIImage(named: "child_radio_selected"), for: .disabled)
        button.sizeToFit()
        button.frame = CGRectMake(0, 0, button.width + margin, button.height)
        return button
    }
    
    /**
    private func joinFamily()
    {
        guard let familyID = _invitationTextField.text , familyID != "" else{
            SVProgressHUD.showError(withStatus:"请输入咿呀门牌号")
            return
        }
        let req = SWJoinFamilyReq()
        req.familyID = familyID
        req.successCallback = {[weak self] response,cache in
            self?.fetchChildrenInfo()
        }
        req.failCallback = {[weak self] error in
            SVProgressHUD.showError(withStatus:"关联失败(\(error.code))")
        }
        load(req)
        SVProgressHUD.show(withStatus: "关联中...")
    }**/
    
    private func createChild()
    {
        let gender:SWGender = SWGender.getGender(rawValue:(_genderGroup.selectedItem as? UIView)?.tag ?? 0)
        let name = _nameTextField.text ?? SW.Config.DefaultKidsName
        let role:Int = (_roleGroup.selectedItem as? UIView)?.tag ?? 0
        
        SWAccountManager.sharedManager().createChild(gender: gender, name: name, birthday: _datePicker.date, role: role, successCallback: {[weak self] in
            self?.loginSuccess()
            }, failCallback: {_ in
                SVProgressHUD.showError(withStatus: "加入失败，请重试")
        })
    }
    
    private func loginSuccess()
    {
        SVProgressHUD.showSuccess(withStatus:"加入成功")
        SWMainApplication.sharedApplication.rootViewController?.showMainContent()
    }
    
    @objc private func cancelBtnTapped()
    {
        _dateTextField.resignFirstResponder()
    }
    
    @objc private func completeBtnTapped()
    {
        let date:NSDate = _datePicker.date as NSDate
        _dateTextField.text = "\(date.year())年\(date.month())月\(date.day())日"
        _dateTextField.resignFirstResponder()
        //print(_datePicker.date)
    }
    
    @objc private func viewTapped()
    {
        view.endEditing(true)
    }
    
    @objc private func createBtnTapped()
    {
        guard let date = _dateTextField.text,date != "" else
        {
            SVProgressHUD.showError(withStatus: "生日未填")
            return
        }
        if _genderGroup.selectedIndex == -1
        {
            SVProgressHUD.showError(withStatus: "性别未填")
            return
        }
        if _roleGroup.selectedIndex == -1
        {
            SVProgressHUD.showError(withStatus: "宝宝关系未填")
            return
        }
        SVProgressHUD.show(withStatus: "加入中...")
        createChild()
    }
    
    @objc private func genderBtnTapped(_ button:UIButton)
    {
        if let button = button as? SWIRadioButton
        {
            _genderGroup.selectItem(button)
        }
    }
    
    @objc private func roleBtnTapped(_ button:UIButton)
    {
        if let button = button as? SWIRadioButton
        {
            _roleGroup.selectItem(button)
        }
    }
    
}
